import type { Commit } from 'vuex';
// 从新文件中导入 MusicState 类型
import type { MusicState } from './music.type'; 
import type { MusicItem } from '@/types/music';
// 引入睡眠监测接口
import { startMonitor, pauseMonitor } from '@/api/sleepMonitor';

// 修改 MusicState 类型，添加 sleepReportId 和 fallAsleepTime 字段
const state: MusicState & { sleepReportId: number | null; fallAsleepTime: Date | null } = {
  musicList: [],
  currentIndex: 0,
  isPlaying: false,
  isMonitoring: false,
  sleepReportId: null,
  fallAsleepTime: null
};


const mutations = {
  UPDATE_MUSIC_LIST(state: MusicState, musicList: MusicItem[]) {
    console.log('更新推荐音乐列表', musicList);
    state.musicList = musicList;
  },
  SET_CURRENT_INDEX(state: MusicState, index: number) {
    state.currentIndex = index;
    const music = state.musicList[index];
    // #ifndef H5
    const audio = uni.getBackgroundAudioManager();
    audio.title = music.name;
    audio.singer = music.singer;
    audio.src = music.url;
    // #endif
    console.log(`设置音乐下标：${state.currentIndex}`);
  },
  SET_IS_PLAYING(state: MusicState, isPlaying: boolean) {
    if (!isPlaying) {
      // 非 H5 平台暂停音频
      // #ifndef H5
      const audio = uni.getBackgroundAudioManager();
      audio.pause();
      // #endif
      console.log(`暂停音乐：${state.musicList[state.currentIndex].name}`);
    } else {
      // #ifndef H5
      const audio = uni.getBackgroundAudioManager();
      // 若音频已结束，从头开始播放
      if (audio.duration === audio.currentTime) {
        audio.seek(0); 
      }
      audio.play();
      // #endif
      console.log(`播放音乐：${state.musicList[state.currentIndex].name} : ${state.musicList[state.currentIndex].url}`);
    }
    state.isPlaying = isPlaying;
  },
  // 新增 mutation
  SET_IS_MONITORING(state: MusicState, isMonitoring: boolean) {
    state.isMonitoring = isMonitoring;
  },
  // 新增 SET_SLEEP_REPORT_ID mutation
  SET_SLEEP_REPORT_ID(state: MusicState & { sleepReportId: number | null }, reportId: number) {
    state.sleepReportId = reportId;
  },
  // 新增 SET_FALL_ASLEEP_TIME mutation
  SET_FALL_ASLEEP_TIME(state: MusicState & { fallAsleepTime: Date | null }, time: Date) {
    state.fallAsleepTime = time;
  }
};

const actions = {
  updateMusicList({ commit }: { commit: Commit }, musicList: MusicItem[]) {
    commit('UPDATE_MUSIC_LIST', musicList);
    commit('SET_CURRENT_INDEX', 0);
  },
  // 播放当前下标音乐
  updateCurrentIndex({ commit }: { commit: Commit }, index: number) {
    commit('SET_CURRENT_INDEX', index);
    commit('SET_IS_PLAYING', true);
  },
  updateIsPlaying({ commit }: { commit: Commit }, isPlaying: boolean) {
    commit('SET_IS_PLAYING', isPlaying);
  },
  // 新增 action
  updateIsMonitoring({ commit }: { commit: Commit }, isMonitoring: boolean) {
    return new Promise((resolve, reject) => {
      commit('SET_IS_MONITORING', isMonitoring);
      if (isMonitoring) {
        startMonitor()
          .then((response) => {
            const reportId = response.data.reportId;
            commit('SET_SLEEP_REPORT_ID', reportId);
            // 记录当前时刻为入睡时间，格式为当前时间戳
            const nowTimestamp = Date.now();
            commit('SET_FALL_ASLEEP_TIME', nowTimestamp);
            console.log(`生成睡眠报告，报告 ID: ${reportId}，入睡时间: ${nowTimestamp}`);
            resolve(response);
          })
          .catch((error) => {
            console.error('启动睡眠监测失败:', error);
            reject(error);
          });
      } else {
        const reportId = state.sleepReportId;
        if (reportId) {
          pauseMonitor(reportId)
            .then(() => {
              commit('SET_SLEEP_REPORT_ID', null);
              commit('SET_FALL_ASLEEP_TIME', null);
              console.log(`取消睡眠报告，报告 ID: ${reportId}`);
              resolve(null);
            })
            .catch((error) => {
              console.error('暂停睡眠监测失败:', error);
              reject(error);
            });
        } else {
          resolve(null);
        }
      }
    });
  },
  // 封装处理音频播放结束的方法
  handleAudioEnded({ commit ,state}: { commit: Commit,state: MusicState }) {
    // 重置音频播放进度
    // #ifndef H5
   const audio = uni.getBackgroundAudioManager();
    if (state.isMonitoring) {
      commit('SET_CURRENT_INDEX', state.currentIndex +1);
    }else{ 
      audio.seek(0); 
      commit('SET_IS_PLAYING', false);
    }
    // #endif
  }
};

const getters = {
  getMusicList: (state: MusicState) => state.musicList,
  getCurrentIndex: (state: MusicState) => state.currentIndex,
  getIsPlaying: (state: MusicState) => state.isPlaying,
  getIsMonitoring: (state: MusicState) => state.isMonitoring,
  getFallAsleepTime: (state: MusicState & { fallAsleepTime: Date | null }) => state.fallAsleepTime
};

export default {
  state,
  mutations,
  actions,
  getters
};